package com.fdb.efp.loan.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.fdb.efp.loan.service.domain.*;
import com.fdb.efp.loan.service.domain.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.util.DateUtility;
import com.fdb.efp.loan.service.dao.AccLoanDao;
import com.fdb.efp.loan.service.dao.AccoutErroTempDao;
import com.fdb.efp.loan.service.dao.GzBankSettleStatusFileTempDao;
import com.fdb.efp.loan.service.dao.LoanSettleStatusDao;
import com.fdb.efp.loan.service.dao.SettleStatusDetailAccountTempDao;
import com.fdb.efp.loan.service.facade.AccoutErroTempService;
import com.fdb.efp.loan.service.facade.LoanSettleStatusService;
import com.fdb.efp.loan.service.vo.LoanSettleStatusVO;

/**
 * <p>
 * ServiceImpl: 马上理赔状态表
 * <p>
 * 
 * @author cyj
 * @date 2018-12-27
 */
@Service("loanSettleStatusService")
public class LoanSettleStatusServiceImpl implements LoanSettleStatusService, FrameworkService {

	private static Logger logger = LoggerFactory.getLogger(LoanSettleStatusServiceImpl.class);

	@Autowired
	private LoanSettleStatusDao loanSettleStatusDao;
	@Autowired
	private GzBankSettleStatusFileTempDao gzBankSettleStatusFileTempDao;
	@Autowired
	private SettleStatusDetailAccountTempDao settleStatusDetailAccountTempDao;
	@Autowired
	private AccLoanDao accLoanDao;
	@Autowired
	private AccoutErroTempDao accoutErroTempDao;
	@Autowired
	private AccoutErroTempService accoutErroTempService;

	/**
	 * 
	 * 同步马上的数据 新增 贷款还款明细 <br>
	 * 0.2:ludayong:2019年3月6日 下午5:10:56:修复对账临时信息为空时，出现空指针异常<br>
	 * @author cenyj
	 * @since 2018年12月28日 下午3:33:37
	 * @date 2019年3月6日 下午5:10:56
	 * @version 0.2
	 */
	public boolean batchBankLoanSettleStatusFromMaTxt() throws Exception {
		boolean rs = false;
		try {
			// 分页大小
			Integer pageSize = 1000;
			// 分页信息
			GzBankSettleStatusFileTemp pageInfo = new GzBankSettleStatusFileTemp();
			// 页数
			int page = 1;
			// pageSize初始化
			if (pageSize > 0) {
				pageInfo.setSize(pageSize);
			} else {
				pageInfo.setSize(1000);
			}
			// 判断循环次数
			int size = gzBankSettleStatusFileTempDao.queryCount();
			String size_msg = "【理赔状态信息表临时表】数据量：" + size;
			logger.info(size_msg, "message{}");
			int loopCount = (size / pageInfo.getSize()) + 1;
			for (int i = 0; i < loopCount; i++) {
				String page_msg = "【理赔状态信息表临时表】当前页数：" + pageInfo.getPage() + "，分页大小：" + pageInfo.getSize();
				logger.info(page_msg, "message{}");
				// 分页查询【理赔状态信息表临时表】数据
				List<GzBankSettleStatusFileTemp> tempList = gzBankSettleStatusFileTempDao.queryByPage(pageInfo);
				if (Objects.nonNull(tempList) && !tempList.isEmpty()) {
					// 分页同步理赔状态信息
					syncLoanSettleStatusInfo(tempList);
				}
				pageInfo.setPage(++page);
			}
			// 先 对账表，看是否能对应上
			//logger.info("日终批量修改从马上同步过来的临时表数据到本地表：");
			//int num = 0;
			// 先校对 对账临时表的记录条数跟同步过来的数据是否一致 如果一致 再批量 把临时表的数据同步到本地
			// 临时表
			//List<GzBankSettleStatusFileTemp> list = gzBankSettleStatusFileTempDao.getGzBankSettleStatusFileTempList();
			//同步信息为空，返回false
			//if(Objects.isNull(list)) {
			//	logger.info("日终批量-同步马上的贷款理赔状态明细信息为空！");
			//	return rs;
			//}
			// 对账列表
			List<SettleStatusDetailAccountTemp> accountList = settleStatusDetailAccountTempDao.getSettleStatusDetailAccountTempList();
			// 对账临时表
			SettleStatusDetailAccountTemp accountTempModel = null;//new SettleStatusDetailAccountTemp();

			int accountCountTemp = 0;// 对账表记录的条数
			int loanTempDatasize = 0;// 实际同步过来的数据总条数
			if (accountList != null && accountList.size() > 0) {
				accountTempModel = accountList.get(0);
			}
			if (accountTempModel != null) {
				accountCountTemp = accountTempModel.getDataAcount() == null ? 0 : accountTempModel.getDataAcount();
			}
			// loanTempDatasize = list.size();
			loanTempDatasize = size;
			logger.info("对账表记录的条数loanTempDatasize：" + loanTempDatasize + "实际同步过来的数据总条数loanTempDatasize" + loanTempDatasize);
			if (loanTempDatasize != accountCountTemp) {
				try {
					// 如果条数不一样，则记录到erro_msg表
					AccoutErroTemp erroMsgModel = new AccoutErroTemp();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String currDate = sdf.format(new Date());
					String erroMsg = "记录条数不对";
					String tableName = "GzBankSettleStatusFileTemp";
					String remark = "同步过来的临时表马上理赔状态表GzBankSettleStatusFileTemp列表记录总条数" + loanTempDatasize + "条" + "对账表记录条数"
							+ accountCountTemp + "条";
					erroMsgModel.setCreateData(currDate);
					erroMsgModel.setErroMsg(erroMsg);
					erroMsgModel.setRemark(remark);
					erroMsgModel.setTableName(tableName);
					accoutErroTempDao.insert(erroMsgModel);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					logger.error("记录同步文件异常信息时出错!");
					String tableName = "LoanRepayDetail还款明细表";
					String erroMsg = "";
					String tempTotal = "";
					String acountTotal = "";
					String type = "0";
					String updateDelInster = "新增";
					String no = "";
					String eMsg = "记录同步文件异常信息时出错!";
					accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);
				}
			}
			rs = true;
		} catch (Exception e) {
			logger.error("理赔状态数据发生异常!", e);
			e.printStackTrace();
			String tableName = "LoanSettleStatus理赔状态明细表";
			String erroMsg = "";
			String tempTotal = "";
			String acountTotal = "";
			String type = "0";
			String updateDelInster = "";
			String no = "";
			String eMsg = e.getMessage();
			accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);

		}
		return rs;
	}

	/**
	 * 新增操作
	 */
	public int insertLoanSettleStatus(LoanSettleStatus inLoanSettleStatus) {
		logger.debug("当前新增数据为:" + inLoanSettleStatus.toString());
		int num = 0;
		try {
			num = loanSettleStatusDao.insertLoanSettleStatus(inLoanSettleStatus);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:" + num);
		return num;
	}

	/**
	 * 删除操作
	 */
	public int deleteByPk(LoanSettleStatusVO inLoanSettleStatusVo) {
		logger.debug("当前删除数据条件为:" + inLoanSettleStatusVo);
		int num = 0;
		try {
			LoanSettleStatus loanSettleStatus = new LoanSettleStatus();
			beanCopy(inLoanSettleStatusVo, loanSettleStatus);
			num = loanSettleStatusDao.deleteByPk(loanSettleStatus);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inLoanSettleStatusVo + "删除的数据条数为" + num);
		return num;
	}

	/**
	 * 更新操作
	 */
	public int updateByPk(LoanSettleStatus inLoanSettleStatus) {
		logger.debug("当前修改数据为:" + inLoanSettleStatus.toString());
		int num = 0;
		try {
			num = loanSettleStatusDao.updateByPk(inLoanSettleStatus);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inLoanSettleStatus + "修改的数据条数为" + num);
		return num;
	}

	/**
	 * 查询操作
	 */
	public LoanSettleStatusVO queryByPk(LoanSettleStatusVO inLoanSettleStatusVo) {

		logger.debug("当前查询参数信息为:" + inLoanSettleStatusVo);
		try {
			LoanSettleStatus queryLoanSettleStatus = new LoanSettleStatus();
			beanCopy(inLoanSettleStatusVo, queryLoanSettleStatus);
			LoanSettleStatus queryRslLoanSettleStatus = loanSettleStatusDao.queryByPk(queryLoanSettleStatus);
			if (Objects.nonNull(queryRslLoanSettleStatus)) {
				LoanSettleStatusVO outLoanSettleStatusVo = beanCopy(queryRslLoanSettleStatus, new LoanSettleStatusVO());
				logger.debug("当前查询结果为:" + outLoanSettleStatusVo.toString());
				return outLoanSettleStatusVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}

	/**
	 * 查询用户权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanSettleStatusVO> queryAllOwner(LoanSettleStatusVO loanSettleStatusVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<LoanSettleStatusVO> list = null;
		try {
			List<LoanSettleStatus> loanSettleStatuss = loanSettleStatusDao.queryAllOwnerByPage(loanSettleStatusVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:" + loanSettleStatuss.size());
			// pageSet(loanSettleStatuss, loanSettleStatusVo);
			list = (List<LoanSettleStatusVO>) beansCopy(loanSettleStatuss, LoanSettleStatusVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 * 查询当前机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanSettleStatusVO> queryAllCurrOrg(LoanSettleStatusVO loanSettleStatusVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<LoanSettleStatus> loanSettleStatuss = loanSettleStatusDao.queryAllCurrOrgByPage(loanSettleStatusVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:" + loanSettleStatuss.size());
		List<LoanSettleStatusVO> list = null;
		try {
			// pageSet(loanSettleStatuss, loanSettleStatusVo);
			list = (List<LoanSettleStatusVO>) beansCopy(loanSettleStatuss, LoanSettleStatusVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<LoanSettleStatusVO> queryAllCurrDownOrg(LoanSettleStatusVO loanSettleStatusVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<LoanSettleStatus> loanSettleStatuss = loanSettleStatusDao.queryAllCurrDownOrgByPage(loanSettleStatusVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:" + loanSettleStatuss.size());
		List<LoanSettleStatusVO> list = null;
		try {
			// pageSet(loanSettleStatuss, loanSettleStatusVo);
			list = (List<LoanSettleStatusVO>) beansCopy(loanSettleStatuss, LoanSettleStatusVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;

	}

	/**
	 *需求编号：【2019D1204】（马上账务文件同步分页处理）
	 *问题编号：【2019D1204】（马上账务文件同步分页处理）
	 *开发人员：【ludayong】
	 *创建日期：【2019/11/27 11:31】
	 *功能描述：分页同步理赔状态信息
	 *修改日期：【2019/11/27 11:31】
	 *修改描述：
	 */
	public void syncLoanSettleStatusInfo(List<GzBankSettleStatusFileTemp> list) {
		try {
			//更新或者新增的记录数
			int num = 0;
			// 本地表进行 新增 或 修改 （状态）
			if (list != null && list.size() > 0) {
				for (GzBankSettleStatusFileTemp fileTemp : list) {
					try {
						/*
						 * 马上传过来的值 为string类型 1 已报案 2 已受理 3 已理赔 是传1 2 3的数字吗？
						 */
						// 判断本地的理赔状态表，没有数据就新增，有数据就修改
						LoanSettleStatus loanSettleStatusby = new LoanSettleStatus();
						loanSettleStatusby.setLoanNo(fileTemp.getLoanNo());
						List<LoanSettleStatus> listLoanSettleStatus = loanSettleStatusDao
								.getLoanSettleStatusListByLoanNo(loanSettleStatusby);
						if (listLoanSettleStatus != null && listLoanSettleStatus.size() > 0) {
							LoanSettleStatus loanSettleStatusM = listLoanSettleStatus.get(0);
							/** 贷款账号（借据号） *//*
							 * loanSettleStatusM.setLoanNo(fileTemp.getLoanNo());
							 * loanSettleStatusM.setReportDate(fileTemp.getReportDate());
							 * loanSettleStatusM.setAcceptDate(fileTemp.getAcceptDate());
							 * loanSettleStatusM.setPayDate(fileTemp.getPayDate());
							 * loanSettleStatusM.setInsurerType(fileTemp.getInsurerType());
							 */
							/** 报案日期 */
							if(fileTemp.getReportDate()!=null)
							{
								loanSettleStatusM.setReportDate(DateUtility.format10To10(fileTemp.getReportDate()));
							}
							/** 受理日期 */
							if(fileTemp.getAcceptDate()!=null)
							{
								loanSettleStatusM.setAcceptDate(DateUtility.format10To10(fileTemp.getAcceptDate()));
							}
							/** 理赔日期 */
							if(fileTemp.getPayDate()!=null)
							{
								loanSettleStatusM.setPayDate(DateUtility.format10To10(fileTemp.getPayDate()));
							}
							/** 保险公司代码 */
							loanSettleStatusM.setInsurerType(fileTemp.getInsurerType());
							/**
							 * Status 状态 String 10 "1 已报案 2 已受理 3 已理赔"
							 */
							loanSettleStatusM.setStatus(fileTemp.getStatus());

							num = updateByPk(loanSettleStatusM);
							if (num == -1) {
								logger.error("修改数据信息出错!");
								String tableName = "LoanSettleStatus理赔还款状态表";
								String erroMsg = "原来的状态为：";
								String tempTotal = "";
								String acountTotal = "";
								String type = "0";
								String updateDelInster = "修改";
								String no = fileTemp.getLoanNo();
								String eMsg = "修改数据信息出错!";
								accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
										eMsg);

							}
						} else {
							// 因爲有可能出现我们审批没有通过，但马上放款的数据，所以先判断本地借据表是否有对应的借据号 有再新增
							AccLoan acc_loan = new AccLoan();
							acc_loan.setBillNo(fileTemp.getLoanNo());
							AccLoan accLoan = accLoanDao.queryByPk(acc_loan);
							if (accLoan != null) {
								SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd");//

								LoanSettleStatus loanSettleStatusM = new LoanSettleStatus();
								/** 贷款账号（借据号） */
								loanSettleStatusM.setLoanNo(fileTemp.getLoanNo());
								/** 报案日期 */
								if(fileTemp.getReportDate()!=null)
								{
									loanSettleStatusM.setReportDate(DateUtility.format10To10(fileTemp.getReportDate()));
								}
								/** 受理日期 */
								if(fileTemp.getAcceptDate()!=null)
								{
									loanSettleStatusM.setAcceptDate(DateUtility.format10To10(fileTemp.getAcceptDate()));
								}
								/** 理赔日期 */
								if(fileTemp.getPayDate()!=null)
								{
									loanSettleStatusM.setPayDate(DateUtility.format10To10(fileTemp.getPayDate()));
								}
								/** 保险公司代码 */
								loanSettleStatusM.setInsurerType(fileTemp.getInsurerType());
								/**
								 * Status 状态 String 10 "1 已报案 2 已受理 3 已理赔"
								 */
								loanSettleStatusM.setStatus(fileTemp.getStatus());// 取字典库数据
								num = insertLoanSettleStatus(loanSettleStatusM);
								if (num == -1) {
									logger.error("新增数据信息出错!");
									String tableName = "LoanSettleStatus理赔还款状态表";
									String erroMsg = "";
									String tempTotal = "";
									String acountTotal = "";
									String type = "0";
									String updateDelInster = "新增";
									String no = fileTemp.getLoanNo();
									String eMsg = "新增数据信息出错!";
									accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster,
											no, eMsg);
								}
							} else {
								logger.info("没有对应的借据数据信息!");
								String tableName = "LoanSettleStatus理赔状态明细表";
								String erroMsg = "";
								String tempTotal = "";
								String acountTotal = "";
								String type = "0";
								String updateDelInster = "新增";
								String no = fileTemp.getLoanNo();
								String eMsg = "没有对应的借据数据信息!";
								accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no,
										eMsg);
							}
						}
					} catch (Exception e) {
						logger.error("新增数据发生异常!", e);
						e.printStackTrace();
						String tableName = "LoanSettleStatus理赔状态明细表";
						String erroMsg = "";
						String tempTotal = "";
						String acountTotal = "";
						String type = "0";
						String updateDelInster = "新增";
						String no = fileTemp.getLoanNo();
						String eMsg = e.getMessage();
						accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);
					}
				}
			}
		} catch (Exception e) {
			logger.error("同步马上理赔状态信息数据发生异常!", e);
		}
	}
}
